package com.partner.boot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.partner.boot.entity.Role;
import com.partner.boot.entity.RolePermission;
import com.partner.boot.exception.ServiceException;
import com.partner.boot.mapper.RoleMapper;
import com.partner.boot.mapper.RolePermissionMapper;
import com.partner.boot.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 菜牙买菜
 * @since 2023-01-17
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private RoleMapper roleMapper;

    @Override
    public void saveRolePermission(Integer roleId, List<Integer> rolePermissions) {
//        if (CollUtil.isEmpty(rolePermissions) || roleId == null) {
//            throw new ServiceException("数据不能为空");
//        }
        rolePermissionMapper.delete(new UpdateWrapper<RolePermission>()
                .eq("role_id", roleId));
        rolePermissions.forEach(v -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(v);
            rolePermissionMapper.insert(rolePermission);
        });
    }

    @Override
    public void saveRole(Role role) {
        Boolean isDefault = role.getIsDefault();
        try {
            if (isDefault) { // 如果设置新添加的角色为新增用户默认角色
                saveRoleIsDefault();
                // 插入新增的角色数据
                roleMapper.insert(role);
            } else {
                roleMapper.insert(role);
            }
        } catch (Exception e) {
            throw new ServiceException("新增角色失败");
        }
    }

    @Override
    public void updateRole(Role role) {
        if (role.getIsDefault()) { // 如果要修改当前角色为默认角色
            saveRoleIsDefault();
            roleMapper.updateById(role);
        } else {
            roleMapper.updateById(role);
        }
     }

    /**
     * 修改角色表中的所有角色都设为不是默认角色
     */
    private void saveRoleIsDefault(){
        // 获取所有角色，将角色都设为不是默认角色
        List<Role> roles = roleMapper.selectList(null);
        for (Role role1 : roles) {
            role1.setIsDefault(false);
            roleMapper.updateById(role1);
        }
    }
}
